import { createDraw } from '@/Utils/createDraw'
import { useMapStore } from '@/stores/map.js'
import { useNoticeStore } from '@/stores/notice.js'
import { Line } from '@/Utils/Line-ES6.js'
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'
const { map } = storeToRefs(useMapStore())
const { noticeScope } = storeToRefs(useNoticeStore())
export const useSingleAnalysis = () => {
  /* ---------------------------- 画笔绘制 --------------------------------------- */
  let draw
  let draw_source = new ol.source.Vector({})
  draw = createDraw({ source: draw_source, type: 'LineString' })
  map.value.addInteraction(draw)
  var vectorData_draw = 'gdbp://MapGisLocal/draw/sfcls/缓冲区画笔'
  draw.on('drawend', () => {
    draw.setActive(false)
    let position = draw.sketchCoords_
    let service = { name: 'draw', layerId: 0 }
    let docLayer = new Zondy.Map.Doc('', 'draw', { crossOrigin: 'Anonymous' })
    let attr = []
    // guanggu图层添加画笔绘制的线
    Line.add({ position, attr, service, docLayer })

    /* ------------------------ 清除上一次的分析图层(地理数据库中的图层) -------------------------------- */
    // 1.查找到要删除图层要素的Fld
    queryByAttribute(vectorData_draw)
    // 2.根据FId删除 --在查询成功的回调中删除 146
    /* --------------------------- 进行缓冲区分析 --------------------------------- */
    singleAnalysis(vectorData_draw)
  })
  /* ------- 缓冲区分析函数 ----------- */
  let resultName_draw = null
  function singleAnalysis(vectorData) {
    /* 1、调用接口创建分析对象 */
    var clsBufBySR = new Zondy.Service.ClassBufferBySingleRing({
      ip: 'localhost',
      port: '6163',
      //经纬度坐标系下,缓冲区的半径单位为度
      leftRad: 0.001,
      rightRad: 0.001,
      //不允许根据属性字段设置缓冲区半径
      isByAtt: false
    })
    /* 设置时间戳,希望分析结果是随机的图层 */
    resultName_draw = vectorData + '缓冲区分析结果' + Date.now()
    //2、设置参数
    //设置源图层
    clsBufBySR.srcInfo = vectorData
    //设置分析结果图层
    clsBufBySR.desInfo = resultName_draw
    //3、 执行分析
    clsBufBySR.execute(onSuccess_singleAnalysis, 'post', false, 'json')
  }
  /* ----- 缓冲区分析成功回调函数 ----- */
  function onSuccess_singleAnalysis(result) {
    if (result.succeed && result.results.length != 0) {
      const resultLayer__singleAnalysis = new Zondy.Map.GdbpLayer('draw', [resultName_draw], {
        ip: 'localhost',
        port: 6163
      })
      map.value.addLayer(resultLayer__singleAnalysis)
      // 移除地图上的分析图层（at(2)--倒数第二个）
      map.value.removeLayer(map.value.getLayers().array_.at(-2))
      /* --------------------------- 进行叠加分析 --------------------------------- */
      let srcInfo1 = 'gdbp://MapGisLocal/wuhan/sfcls/居民区'
      let srcInfo2 = result.results[0].Value
      clipByLayerAnalysis(srcInfo1, srcInfo2)
    }
  }
  /* --------- 叠加分析函数 ------------ */
  let resultName_neighborhood = null
  function clipByLayerAnalysis(srcInfo1, srcInfo2) {
    resultName_neighborhood = srcInfo1 + '叠加分析结果' + Date.now()
    //2.2 创建叠加分析服务
    var clipParam = new Zondy.Service.ClipByLayer({
      ip: 'localhost',
      port: '6163',
      //设置被叠加图层URL
      srcInfo1,
      srcInfo2,
      //设置结果URL
      desInfo: resultName_neighborhood,
      //设置结果图层的图形参数信息
      infoOptType: 1,
      //求交
      overType: 1,
      //允许重算面积
      isReCalculate: true,
      //容差半径
      radius: 0.05
    })
    //2.3 执行叠加分析
    //调用基类的execute方法,执行叠加分析,onSuccess为结果回调函数
    clipParam.execute(
      onSuccess_clipByLayerAnalysis,
      'post',
      false,
      'json',
      onError_clipByLayerAnalysis
    )
  }
  /* ------- 叠加分析成功回调函数 -------- */
  function onSuccess_clipByLayerAnalysis(result) {
    if (result.succeed && result.results.length != 0) {
      const resultLayer_neighborhood = new Zondy.Map.GdbpLayer('', [resultName_neighborhood], {
        ip: 'localhost',
        port: '6163'
      })
      /* ------------------------ 查询叠加区对应图层的属性 -------------------------- */
      queryByAttribute(result.results[0].Value)
    }
  }
  /* ------- 叠加分析失败回调函数 -------- */
  function onError_clipByLayerAnalysis(err) {
    console.log(err)
  }
  /* ------- 叠加区图层的查询函数 -------- */
  function queryByAttribute(vectorData_overlay) {
    //初始化查询结构对象，设置查询结构包含几何信息
    var queryStruct = new Zondy.Service.QueryFeatureStruct()
    queryStruct.IncludeGeometry = true
    //实例化查询参数对象
    var queryParam = new Zondy.Service.QueryByLayerParameter(vectorData_overlay, {
      resultFormat: 'json',
      struct: queryStruct
    })
    //设置查询分页号
    queryParam.pageIndex = 0
    //设置查询要素数目
    queryParam.recordNumber = 200

    //实例化地图文档查询服务对象
    var queryService = new Zondy.Service.QueryLayerFeature(queryParam, {
      ip: 'localhost',
      port: '6163' //访问IGServer的端口号，.net版为6163，Java版为8089
    })
    //执行查询操作，querySuccess为查询回调函数
    queryService.query(querySuccess, queryError)
  }
  /* ---------- 查询成功回调 ------------- */
  function querySuccess(result) {
    if (result.AttStruct.FldNumber == 2) {
      const featureIds = result.SFEleArray.map((item) => item.FID)
      featureIds.pop()
      deleteLine(featureIds)
      return
    } else if (result.AttStruct.FldNumber == 6) {
      noticeScope.value = result.SFEleArray.map((item) => {
        return {
          name: item.AttValue[4],
          tel: item.AttValue[5]
        }
      })
      ElMessage({
        message: '分析成功，请前往《发布公告》查看结果',
        type: 'success',
        duration: 1500
      })
      return
    }
  }
  /* ---------- 查询失败回调 ------------- */
  function queryError(e) {
    alert('查询失败')
    console.log(e)
  }
  /* ---------- 清除缓冲区画笔要素 ------------- */
  function deleteLine(featureIds) {
    var deleteService = new Zondy.Service.EditLayerFeature(
      'gdbp://MapGisLocal/draw/sfcls/缓冲区画笔',
      {
        ip: 'localhost',
        port: '6163'
      }
    )
    deleteService.deletes(featureIds, onLineSuccess)
  }
  /* ----------- 删除线要素回调函数 ------------- */
  function onLineSuccess(data) {
    if (data.succeed) {
    }
  }
}
